import React from 'react'
import { Modal, Form, Select, message, Spin, Empty, Input, Upload, Button, DatePicker } from 'antd'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { UploadOutlined } from '@ant-design/icons'
import { connect } from 'react-redux'
import moment from 'moment'
import style from './OperateModal.module.less'
import { getUploadProps } from '@js/tool'

const { Item } = Form
const { TextArea } = Input
const { Option } = Select

class OperateModal extends Component {
  state ={
    caseList: [],
    loading: false,
    fileList: []
  }

  formRef = React.createRef()

  // 获取案件列表数据
  getCaseData (s) {
    this.timer && clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      this.setState({ loading: true })
      this.$get('/api/xapc/case', {
        condition: JSON.stringify([{ k: 'caseno_desc', o: 'like', v: `%${s}%` }])
      }).then(res => {
        this.setState({ loading: false })
        if (res.status === 1) {
          this.setState({
            caseList: res.data.list
          })
        } else {
          message.warning(res.message)
        }
      }).catch(() => this.setState({ loading: false }))
    }, 500)
  }

  // 修改案号
  changeCaseno (e) {
    let id = ''
    const list = this.state.caseList
    for (let i = 0; i < list.length; i++) {
      if (list[i].caseno_desc === e) {
        id = list[i].id
      }
    }
    this.formRef.current.setFieldsValue({
      caseid: id,
      caseno_desc: e
    })
  }

  // 修改处理人
  changePerson (e) {
    let id = ''
    const list = this.props.personList
    for (let i = 0; i < list.length; i++) {
      if (list[i].name === e) {
        id = list[i].id
      }
    }
    this.formRef.current.setFieldsValue({
      updaterid: id,
      updater: e
    })
  }

  // 初始表单数据
  initData () {
    const d = this.props.data
    const c = this.formRef.current
    if (c) {
      this.setState({ fileList: [], caseList: [], loading: false })
      c.resetFields()
      const keys = Object.keys(d)
      const r = {}
      keys.forEach(k => {
        if (d[k]) {
          r[k] = d[k]
        }
      })
      if (r.update_datetime) {
        r.update_datetime = moment(r.update_datetime * 1000)
      }
      c.setFieldsValue(r)
    } else {
      setTimeout(() => {
        this.initData()
      }, 100)
    }
  }

  componentDidUpdate (prev) {
    if (!prev.visible && this.props.visible) {
      this.initData()
    }
  }

  // 当加载中，渲染加载动画
  renderNotFound () {
    if (this.state.loading) {
      return <div className={style['loading-box']}><Spin /></div>
    }
    return <div className={style['loading-box']}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>
  }

  // 选入修改部分表单
  renderModifyForm () {
    if (!this.props.data.id) {
      return null
    }
    return (
      <>
        <Item noStyle name='updaterid'><span /></Item>
        <Item label='处理人' name='updater' rules={[{ required: true, message: '处理人不能为空' }]}>
          <Select placeholder='请选择处理人' onChange={e => this.changePerson(e)} showSearch allowClear>
            {this.props.personList.map((li, i) => <Option key={i} value={li.name}>{li.name}</Option>)}
          </Select>
        </Item>
        <Item label='处理完成时间' name='update_datetime' rules={[{ required: true, message: '处理完成时间不能为空' }]}>
          <DatePicker placeholder='请选择处理完成时间' className={style.full} />
        </Item>
        <Item label='处理结果' name='handing_result' rules={[{ required: true, message: '处理结果不能为空' }]}>
          <TextArea placeholder='请输入处理结果' />
        </Item>
      </>
    )
  }

  render () {
    return (
      <Modal
        title={this.props.id ? '修改信访' : '新增信访'}
        open={this.props.visible}
        onOk={() => this.formRef.current.submit()}
        onCancel={() => this.props.hide()}
        okText='确定'
        cancelText='取消'
        destroyOnClose
      >
        <Form labelCol={{ flex: '110px' }} ref={this.formRef} onFinish={d => this.props.onFinish(d)}>
          <Item noStyle name='id'><span /></Item>
          <Item noStyle name='caseid'><span /></Item>
          <Item label='案号' name='caseno_desc' rules={[{ required: true, message: '案号不能为空' }]}>
            <Select placeholder='请选择案号' onSearch={e => this.getCaseData(e)} onChange={e => this.changeCaseno(e)} showSearch showArrow={false} allowClear notFoundContent={this.renderNotFound()}>
              {this.state.caseList.map(li => <Option key={li.id} value={li.caseno_desc}>{li.caseno_desc}</Option>)}
            </Select>
          </Item>
          <Item label='信访内容' name='remark' rules={[{ required: true, message: '信访内容不能为空' }]}>
            <TextArea placeholder='请输入信访内容' />
          </Item>
          {this.renderModifyForm()}
          <Item name='file' label='相关附件'>
            <Upload {...getUploadProps.call(this, this.formRef)}>
              <Button disabled={this.state.fileList.length > 8}>
                <UploadOutlined /> 上传文件
              </Button>
            </Upload>
          </Item>
        </Form>
      </Modal>
    )
  }
}

OperateModal.propTypes = {
  visible: PropTypes.bool,
  hide: PropTypes.func,
  onFinish: PropTypes.func,
  id: PropTypes.string,
  data: PropTypes.object,
  personList: PropTypes.array
}

OperateModal.defaultProps = {
  visible: false,
  hide: function () {},
  onFinish: () => {},
  id: '',
  data: {},
  personList: []
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(OperateModal)
